package com.spillman.signtab.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.spillman.signtab.R;
import com.spillman.signtab.preferences.MainPreference;
import com.spillman.signtab.preferences.MainPreferenceActivity;
import com.spillman.signtab.utils.ExtensionFilenameFilter;
import com.spillman.signtab.utils.FileComparator;
import com.spillman.signtab.utils.MyAdmin;

public class WelcomePage extends Activity {

	static final int RESULT_ENABLE = 1;
	private Context mContext;
	protected File mDirectory = new File(Environment.getExternalStorageDirectory() + "/bluetooth");
	protected ArrayList<File> mFiles;
	public static String DOCUMENT_LOCATION;
	private static final String SAVE_DIR = Environment.getExternalStorageDirectory() + "/dcim/SignTab/";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFiles = new ArrayList<File>();
		mContext = this;
		setContentView(R.layout.welcome_page);
		init();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			startActivity(new Intent(this, MainPreferenceActivity.class));
			break;
		}

		return true;
	}

	@Override
	protected void onStart() {
		super.onStart();
		SharedPreferences prefs = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
		checkPrefs(prefs);
	}
	
	private void init() {
		PreferenceFragment edits = new MainPreference();
		getFragmentManager().beginTransaction().add(R.id.settings_frame, edits).commit();
		findViewById(R.id.get_document_button).setOnClickListener(btListener);
		findViewById(R.id.picture_button).setOnClickListener(photoIntent);
		findViewById(R.id.audio_button).setOnClickListener(demoListener);
		findViewById(R.id.sign_button).setOnClickListener(signIntent);
		
		File storageDir = null;
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			storageDir = new File(SAVE_DIR);
			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("Sign", "failed to create directory");
					}
				}
			}
		} else {
			Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.landing_page_menu, menu);
		return true;
	}

	private void checkPrefs(SharedPreferences prefs) {
		if (prefs.getBoolean(getString(R.string.pref_key_first_run), true)) {
			prefs.edit().putBoolean(getString(R.string.pref_key_first_run), false).commit();
			displayRequest();
		}
	}

	private void displayRequest() {
		Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
		intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, new ComponentName(this, MyAdmin.class));
		intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "This device require device admin for locking )");
		startActivityForResult(intent, RESULT_ENABLE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case RESULT_ENABLE:
			if (resultCode == Activity.RESULT_OK) {
				updatePreferences();
			} else {
				Toast.makeText(this, "Admin was not enabled, you can try change it from settings )", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	private void updatePreferences() {
		SharedPreferences prefs = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
		prefs.edit().putBoolean(getString(R.string.pref_key_admin_enabled), true).commit();
	}

	private View.OnClickListener demoListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			Toast.makeText(mContext, R.string.unavailable_option, Toast.LENGTH_SHORT).show();
		}
	};

	private View.OnClickListener btListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			getFiles();
			selectAndMoveLastFile();
			if(DOCUMENT_LOCATION != null && !DOCUMENT_LOCATION.equals("")){
				findViewById(R.id.sign_button).setEnabled(true);
			}
		}

	};

	private void selectAndMoveLastFile() {
		long max = 0;
		int lastModifiedId = 0;
		if (mFiles.size() > 0) {
			for (int i = 0; i < mFiles.size(); i++) {
				if (mFiles.get(i).lastModified() > max) {
					lastModifiedId = i;
					max = mFiles.get(i).lastModified();
				}
			}
			try {
				DOCUMENT_LOCATION = Environment.getExternalStorageDirectory() + "/dcim/SignTab/"
						+ mFiles.get(lastModifiedId).getName();
				copyFile(mFiles.get(lastModifiedId), new File(DOCUMENT_LOCATION));
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(this, "Error while copy the file", Toast.LENGTH_SHORT).show();
			}
			mFiles.get(lastModifiedId).delete();
			Toast.makeText(this, "Document was moved to application directory", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "Empty directory", Toast.LENGTH_SHORT).show();
		}
	}

	public void copyFile(File sourceLocation, File targetLocation) throws IOException {

		InputStream in = new FileInputStream(sourceLocation);
		OutputStream out = new FileOutputStream(targetLocation);

		// Copy the bits from instream to outstream
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
	}

	private void getFiles() {
		// Clear the files ArrayList
		mFiles.clear();

		// Set the extension file filter
		ExtensionFilenameFilter filter = new ExtensionFilenameFilter(new String[] { ".pdf" });

		// Get the files in the directory
		File[] files = mDirectory.listFiles(filter);
		if (files != null && files.length > 0) {
			for (File f : files) {
				if (f.isHidden()) {
					// Don't add the file
					continue;
				}
				// Add the file the ArrayAdapter
				mFiles.add(f);
			}
			Collections.sort(mFiles, new FileComparator());
		}
	}

	private View.OnClickListener signIntent = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(mContext, ItemListActivity.class);
			mContext.startActivity(intent);
		}
	};

	private View.OnClickListener photoIntent = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(mContext, PhotoIntentActivity.class);
			mContext.startActivity(intent);
		}
	};

}
